<template>
  <div>

    <div class="editorWarp" @contextmenu.prevent.stop="">
      <Myheader :layout-data='layoutData'></Myheader>
      <ui-dock v-if="layoutData" :info="layoutData"></ui-dock>
    </div>

  </div>
</template>

<script>
// import '@/assets/style/element-variables.scss'
import Myheader from '@/widgets/components/Header'
import UiDock from '@/widgets/components/dock/index'
import { mapState } from 'vuex'
import cloneDeep from 'lodash/cloneDeep'
import common from '@/assets/js/common'
// import emptyPage from '@/assets/data/empty.json'
import propsLib from '@/widgets/helper/setting/props'
import tablePropsLib from '@/widgets/helper/setting/tableProps'
// import FormsMixin from '@/base/mixin/forms'
import { getForms, updateForms } from '@/widgets/helper/storage'
// import EMA from '@/assets/js/singleton-ema'
import { getInfo } from '@/api/tpl';

export default {
  // mixins: [FormsMixin],
  components: {
    Myheader,
    UiDock
  },
  data() {
    return {
      model: null,
      layoutData: null,
      nodeInfo: null,
    }
  },
  props: ['active'],
  computed: {
    ...mapState({
      form: state => state.formModel,
      fields: state => state.fields,
      currentLayout: state => state.viewOption.currentLayout,
      demoMode: state => state.setting.demoMode
    }),
    query_types() {
      return this.$route.query.types;
    }
  },
  watch: {
    nodeInfo: function (params) {
      this.$store.dispatch('user/setNodeinfo', params);
    },
    currentLayout: {
      handler(val, oldVal) {
        this.layout(val)
      },
      immediate: true
    },
    query_types: {
      handler(val, oldVal) {
        if(val!=oldVal){
          this.initquid();
        }

      },
    }
  },
  created() {
    window.EMA = window.EMA;

    this.initquid();


    // const id = this.$route.params.id
    // if (id) {

    //   if (LOCAL_STORAGE) {
    //     const model = getForms(id)
    //     this.$store.commit('setFormModel', model.config || formSetting.model)
    //     this.$store.commit('setFields', model.fields || [])
    //   } else {
    //     this.getForms(id).then(res => {
    //       // 表单配置
    //       this.$store.commit('setFormModel', res.config || formSetting.model)
    //       this.$store.commit('setFields', res.fields || [])
    //     }).catch(e => {
    //       console.log(e.message)
    //     })
    //   }
    // }
    // this.$store.commit('setProps', propsLib)
    // this.$store.commit('addTabsField', {
    //  field: {
    //       title: '基本配置',
    //       id: '0',
    //       content: []
    //     },
    //   index:0
    // });
  },
  mounted() {
    // this.nodeInfo = {};
    this.bindEvent()
    this.layout();
    this.loadPageInfo()
  },
  methods: {
    async initquid() {
      const id = this.$route.query.id;
      if (id) {
        await this.getForms(id);
      } else {
        console.log('-----------------------------')
        this.$store.commit('setFields', [{
            title: '基本配置',
            id: '0',
            content: []
          }])
      }

      this.$store.commit('setProps', propsLib)
      this.$store.commit('setTableProps', tablePropsLib)
    },
    async getForms(id) {
      // console.log('-----------------------------')
      var d = { id: id };
      const res = await getInfo(d);
      // console.log('-----------------------------',res)
      if (res && res.code === 200) {
        // console.log(res.data.info.template_content,'================================================================')
        // console.log(res.data.info.template_content['searchForm'],'================================================================')
        if(this.query_types==2){
          // console.log(res.data.info.template_content['leftButton'],'================================================================')
          this.$store.commit('setFields', res.data.info.template_content['searchForm'] || [])
          this.$store.commit('setTableFields', res.data.info.template_content['table'] || [])
          this.$store.commit('setButtonFields', {
            list:res.data.info.template_content['leftButton'] || [],
            type:'left'
          })
          this.$store.commit('setButtonFields', {
            list:res.data.info.template_content['rightButton'] || [],
            type:'right'
          })
          
        }else{
          this.$store.commit('setFields', res.data.info.template_content || [])
        }

        console.log(this.fields,res.data.info)
        this.$store.commit('addSubFromField', {
          is_footer: res.data.info.is_footer,
          ajax_url: res.data.info.ajax_url,
          alias: res.data.info.alias,
          index_url: res.data.info.index_url,
          note: res.data.info.note,
          id: res.data.info.id,
          template_type: res.data.info.template_type,
          title: res.data.info.title,
          status: res.data.info.status,
        });
      } else {
        this.$store.commit('setFields', [])
      }

      this.$store.commit('setProps', propsLib)
    },

    async layout() {
      let layoutOptions
      layoutOptions = await import(
        /* webpackMode: "eager" */
        /* webpackInclude: /\.json$/ */
        `@/assets/layout/default.json`
      )
      layoutOptions = cloneDeep(layoutOptions.default || layoutOptions)
      this.layoutData = layoutOptions;
    },
    /**
       * 加载页面内容信息
       * @augments
       */
    loadPageInfo: function () {
      var urlInfo = common.parseURL(window.location.href)
      console.log(!urlInfo.params.key, 6666666)
      if (!urlInfo.params.key) {
        if (process.env.NODE_ENV == 'production') this.$alert('编辑页面缺少key')
        else {
          this.nodeInfo = cloneDeep({})
          console.log(this.nodeInfo, 6666)
          this.$store.dispatch('SettingChange', { demoMode: true })
        }
        return
      }
      var keys = this.keys = urlInfo.params.key.split('/')
      if (keys.length == 1) {
        keys[1] = keys[0]
      }
      Server({
        url: 'editor/pages/editor-detail',
        method: 'post', // default
        needLoading: false,
        data: {
          pageKey: keys[1],
          scene: 'edit',
        }
      }).then((respond) => {
        var data = respond.data
        this.pageInfo = data.data
        var info = null
        try {
          info = JSON.parse(this.pageInfo.content) || {}
        } catch (error) {
        }
        this.$store.dispatch('setPageType', this.pageInfo.type)
        if (info.canvas && info.canvas.width) this.$store.dispatch('SettingChange', { phoneSize: info.canvas })
        this.nodeInfo = cloneDeep(info)
        this.$store.dispatch('setUser', { userId: data.data && data.data.uid })
      })
    },
    bindEvent: function () {
      // loading
      let $loading
      console.log(window)
      window.EMA.bind('loading.show', () => {
        $loading = this.$loading({
          lock: true,
          text: '处理中，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      })
      window.EMA.bind('loading.hide', () => {
        $loading && $loading.close()
      })
      var me = this


      // 绑定替换页面模板信息
      // TODO:这个没什么用
      window.EMA.bind('selectPageTemplate', (content) => {
        console.log(content, 88888888)
        if (content) {
          Object.assign(this.nodeInfo, cloneDeep(content))
        }
      })
      // 保存页面
      window.EMA.bind('pageInfo.save', (fast, callback) => {
        console.log('save---------', this.nodeInfo)
        this.doSave(this.nodeInfo, true)
        // if (this.demoMode) return this.$alert('您处在 demo 模式下，不能保存数据哦')
        this.savePage(fast, callback)
      })

      // TODO:这个也没什么用
      // 绑定组件点击添加组件到根元素
      window.EMA.bind('commponent.addOne', menu => {
        var selectNode = this.nodeInfo
        if (window.$vue && window.$vue.nodeInfo) {
          selectNode = window.$vue.nodeInfo
        }
        var nodeInfo = getBaseNode(menu)
        let judge = common.componentAddJudge(selectNode, window.$vue || this)
        if (!judge.can) return this.$alert(judge.msg)
        // 如果给page容器添加孩子元素。孩子元素需要占满全屏
        if ((/pageContainer$/i).test(selectNode.type)) {
          nodeInfo.forceStyle = {
            position: 'absolute',
            width: '100%',
            height: '100%',
            left: '0',
            top: '0'
          }
        }
        if (!selectNode.child) {
          this.$set(selectNode, 'child', [])
        }
        selectNode.child.push(nodeInfo)
      })


      // 按键
      window.document.addEventListener('keydown', (e) => {
        var keyCode = e.keyCode
        switch (keyCode) {
          case 38:
            window.EMA.fire('arrowup.down', e)
            break
          case 40:
            window.EMA.fire('arrowdown.down', e)
            break
          case 37:
            window.EMA.fire('arrowleft.down', e)
            break
          case 39:
            window.EMA.fire('arrowright.down', e)
            break
          case 8:
            window.EMA.fire('delete.down', e)
          case 46:
            window.EMA.fire('delete.down', e)
            break
          case 18:
            window.EMA.fire('alt.down', e)
            break
          case 16:
            window.EMA.fire('shift.down', e)
            break
        }
      })
      window.document.addEventListener('keyup', (e) => {
        var keyCode = e.keyCode
        switch (keyCode) {
          case 8:
          case 46:
            window.EMA.fire('delete.up', e)
            break
          case 18:
            window.EMA.fire('alt.up', e)
            break
          case 16:
            window.EMA.fire('shift.up', e)
            break
          case 70:
            if (e.ctrlKey && e.shiftKey) {
              window.EMA.fire('ctrl.shift.f.up', e)
              e.preventDefault()
            }
            break
        }
      })
    },
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" type="text/stylus">






.editorWarp {
  width: 100%;
  height: 100%;
  left: 0;
  bottom: 0;
  position: absolute;
  display: flex;
  flex-direction: column;
}


</style>


